package com.pms.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.entity.EntranceDoor;
import com.pms.entity.EstateAgency;
import com.pms.entity.OwnerMember;
import com.pms.entity.UnitHouse;
import com.pms.exception.R;
import com.pms.rpc.CnareaSevice;
import com.pms.service.*;
import com.pms.util.ValidateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import com.pms.controller.BaseController;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * 物业机构 因关联数据较多  暂无删除
 * </p>
 *
 * @author ASUS_B
 * @since 2017-10-26
 */
@RestController
@RequestMapping("/estateAgencyBase")
@Api(value = "物业机构管理界面接口", description = "物业机构管理界面接口")
public class EstateAgencyController extends BaseController {
    @Autowired
    private IEstateAgencyService estateAgencyService;
    @Autowired
    private IUnitHouseService unitHouseService;
    @Autowired
    private IEntranceDoorService entranceDoorService;
    @Autowired
    private CnareaSevice cnareaSevice;
    @Autowired
    private IOwnerMemberService ownerMemberService;
    @Autowired
    private IEstateDoorLockService estateDoorLockService;
    @ApiOperation(value = "添加物业/社区")
    @RequestMapping(value = "/addEstateAgency", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "agencyName", value = "物业/社区名称", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "agencyType", value = "类型((1物业-默认|2社区))", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "parentId", value = "上级id(默认0)，类型为社区必传", required = false, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "areaId", value = "机构所在地址id(省-市-区)", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "areaLongitude", value = "地址经度值", required = false, dataType = "double", paramType = "form"),
            @ApiImplicitParam(name = "areaLatitude", value = "地址纬度值", required = false, dataType = "double", paramType = "form"),
            @ApiImplicitParam(name = "agencyPhone", value = "联系电话-手机", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "agencyTelphone", value = "联系电话-座机", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "agencyAddressDetail", value = "地址补充信息", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "agencyImg", value = "机构主图url", required = false, dataType = "String", paramType = "form"),
    })
    public R addEstateAgency(String agencyName, Integer agencyType, Long parentId, String areaId, Double areaLongitude, Double areaLatitude
            , String agencyPhone, String agencyTelphone, String agencyAddressDetail, String agencyImg) {
        parameterIsBlank(agencyName, "请填写机构名称");
        if (null == agencyType || agencyType != 2) {
            agencyType = 1;
        }
        if (null != parentId) {
            if (agencyType == 2) {
                EstateAgency estateAgency = estateAgencyService.selectById(parentId);
                parameterIsNull(estateAgency, "没有该上级机构信息");
            }
            if (agencyType == 1) {
                parentId = 0L;
            }
        }
        if (null == parentId) {
            if (agencyType == 1) {
                parentId = 0L;
            }
            if (agencyType == 2) {
                return R.error(400, "请选择该社区上级物业");
            }
        }
        int countAgencyName = 0;
        Integer communityNum = null;
        if (agencyType == 1) {
            countAgencyName = estateAgencyService.selectCount(new EntityWrapper<EstateAgency>().eq("agency_name", agencyName));
        }
        if (agencyType == 2) {
            countAgencyName = estateAgencyService.selectCount(new EntityWrapper<EstateAgency>().eq("agency_name", agencyName).eq("parent_id", parentId));
            communityNum = estateAgencyService.selectMaxCommunityNum();
        }
        if (countAgencyName > 0) {
            return R.error(400, "该机构名称已存在");
        }
        if (StringUtils.isBlank(agencyPhone) && StringUtils.isBlank(agencyTelphone)) {
            return R.error(400, "机构联系电话必须有一个");
        }
        if (StringUtils.isNotBlank(agencyPhone)) {
            if (!ValidateUtil.validatePhone(agencyPhone)) {
                return R.error(400, "联系电话(手机)格式错误");
            }
        }
        if (StringUtils.isNotBlank(agencyTelphone)) {
            if (!ValidateUtil.validateTelphone_(agencyTelphone)) {
                return R.error(400, "联系电话(座机)格式错误");
            }
        }
        parameterIsBlank(areaId, "请选择机构地址");
        /*
         * 验证 机构地址 是否存在  获取编号对应的地址信息
         */
        String[] areaIdArr = areaId.split("-");
        if (areaIdArr.length < 3) {
            return R.error(400, "请选择完整机构地址");
        }
        for (int x = 0; x < areaIdArr.length; x++) {
            areaIdArr[x] = areaIdArr[x].trim();
        }
        EstateAgency addEstateAgency = new EstateAgency();
        try {
            Long threeAreaId = Long.parseLong(areaIdArr[2]);
            Map<String, Object> areaInfoMap = cnareaSevice.selectThreeParentArea(threeAreaId);
            if (null == areaInfoMap) {
                return R.error(400, "未查询到该地址信息");
            }
            if (areaIdArr[1].equals(areaInfoMap.get("twoAreaId").toString()) && areaIdArr[0].equals(areaInfoMap.get("oneAreaId").toString())) {
                addEstateAgency.setAgencyAddress("" + areaInfoMap.get("oneAreaName") + areaInfoMap.get("twoAreaName") + areaInfoMap.get("threeAreaName"));
                addEstateAgency.setAreaLongitude(Double.parseDouble(areaInfoMap.get("threeAreaLng").toString()));
                addEstateAgency.setAreaLatitude(Double.parseDouble(areaInfoMap.get("threeAreaLat").toString()));//设置机构地址经纬度
                addEstateAgency.setAreaId(areaIdArr[0] + "-" + areaIdArr[1] + "-" + areaIdArr[2]);//设置机构地址编号
            } else {
                return R.error(400, "错误的地址信息");
            }
        } catch (NumberFormatException ex) {
            return R.error(400, "错误的地址信息");
        } catch (NullPointerException ex) {
            return R.error(400, "未查询到该地址信息");
        }
        addEstateAgency.setAgencyAddressDetail(agencyAddressDetail);//设置机构地址补充信息
        addEstateAgency.setAgencyImg(agencyImg);//设置机构图片url
        addEstateAgency.setAgencyPhone(agencyPhone);//设置机构联系电话
        addEstateAgency.setAgencyTelphone(agencyTelphone);//设置机构联系电话
        addEstateAgency.setAgencyName(agencyName);//设置机构名称
        addEstateAgency.setAgencyState(1);// 默认机构启用
        addEstateAgency.setAgencyType(agencyType);// 设置机构类型
        addEstateAgency.setParentId(parentId);// 设置上级机构
        addEstateAgency.setCommunityNum(communityNum);
        addEstateAgency.setCommunityPassword(estateAgencyService.randomHexString(12));// 生成12位的16进制密码
//        addEstateAgency.setCreateBy();
        addEstateAgency.setCreateTime(new Date());

        /*=======添加百度LBS数据=======*/
        //        addEstateAgency.setLbsPoiId(); //设置机构地址LBS数据id
        estateAgencyService.insert(addEstateAgency);
        if (addEstateAgency.getAgencyType() == 2) {//创建物业办公室
            UnitHouse estateHouse = new UnitHouse();
            estateHouse.setIsEstateHouse(1);//设置为物业办公室
            estateHouse.setIsShowApp(1);
            estateHouse.setIsHaveMember(2);//设置无会员认证
            estateHouse.setIsHaveMaster(2);//设置无户主信息
            estateHouse.setCommunityId(addEstateAgency.getAgencyId());
            estateHouse.setAgencyId(addEstateAgency.getParentId());
            estateHouse.setHouseSort(0);
            estateHouse.setFloorSort(0);
            estateHouse.setHouseNumber("物业办公室");
            estateHouse.setUnitName("");
            unitHouseService.insert(estateHouse);
            //创建小区大门
            EntranceDoor door = new EntranceDoor().setDoorName("大门").setDoorType(1).setCommunityId(addEstateAgency.getAgencyId())
                    .setAgencyId(addEstateAgency.getParentId()).setCommunityNum(addEstateAgency.getCommunityNum())
                    .setUnitNum(0).setIsHaveLock(2);
            entranceDoorService.insert(door);
        }
        return R.ok();
    }

    @ApiOperation(value = "修改物业/社区")
    @RequestMapping(value = "/editEstateAgency", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "agencyId", value = "物业/社区id", required = true, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "agencyName", value = "物业/社区名称", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "agencyType", value = "类型((1物业-默认|2社区))", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "parentId", value = "上级id(默认0),修改类型时必传", required = false, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "areaId", value = "地址id(省id-市id-区id)", required = false, dataType = "string", paramType = "form"),
            @ApiImplicitParam(name = "areaLongitude", value = "地址经度值", required = false, dataType = "double", paramType = "form"),
            @ApiImplicitParam(name = "areaLatitude", value = "地址纬度值", required = false, dataType = "double", paramType = "form"),
            @ApiImplicitParam(name = "agencyPhone", value = "联系电话-手机", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "agencyTelphone", value = "联系电话-座机", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "agencyAddressDetail", value = "地址补充信息", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "agencyImg", value = "机构主图url", required = false, dataType = "String", paramType = "form"),
    })
    public R editEstateAgency(String agencyId, String agencyName, Integer agencyType, Long parentId, String areaId, Double areaLongitude, Double areaLatitude
            , String agencyPhone, String agencyTelphone, String agencyAddressDetail, String agencyImg) {
        parameterIsBlank(agencyId, "机构id不能为空");
        EstateAgency oldEstateAgency = estateAgencyService.selectById(agencyId);
        parameterIsNull(oldEstateAgency, "暂无该机构信息");
        boolean editTag = false;
        /* ==== 地址补充信息=====*/
        if (StringUtils.isNotBlank(agencyAddressDetail)) {
            if (!agencyAddressDetail.equals(oldEstateAgency.getAgencyAddressDetail())) {
                editTag = true;
                oldEstateAgency.setAgencyAddressDetail(agencyAddressDetail);
            }
        }
         /* ==== 机构图片=====*/
        if (StringUtils.isNotBlank(agencyImg)) {
            if (!agencyImg.equals(oldEstateAgency.getAgencyImg())) {
                editTag = true;
                oldEstateAgency.setAgencyImg(agencyImg);
            }
        }
         /* ==== 机构联系电话=====*/
        if (StringUtils.isNotBlank(agencyPhone)) {
            if (StringUtils.isNotBlank(agencyPhone)) {
                if (!ValidateUtil.validatePhone(agencyPhone)) {
                    return R.error(400, "联系电话(手机)格式错误");
                }
            }
            if (!agencyPhone.equals(oldEstateAgency.getAgencyPhone())) {
                editTag = true;
                oldEstateAgency.setAgencyPhone(agencyPhone);
            }
        }
        if (StringUtils.isNotBlank(agencyTelphone)) {
            if (StringUtils.isNotBlank(agencyTelphone)) {
                if (!ValidateUtil.validateTelphone_(agencyTelphone)) {
                    return R.error(400, "联系电话(座机)格式错误");
                }
            }
            if (!agencyTelphone.equals(oldEstateAgency.getAgencyTelphone())) {
                editTag = true;
                oldEstateAgency.setAgencyTelphone(agencyTelphone);
            }
        }
         /* ==== 机构类型(上级机构)=====*/
        if (null != agencyType) {
            if (agencyType != 1 && agencyType != 2) {
                return R.error(400, "机构类型超出范围");
            }
            if (agencyType != oldEstateAgency.getAgencyType()) {
                if (null != parentId) {
                    if (agencyType == 1) {
                        parentId = 0L;
                    }
                    if (agencyType == 2) {
                        EstateAgency estateAgency = estateAgencyService.selectById(parentId);
                        parameterIsNull(estateAgency, "没有该上级机构信息");
                        if (estateAgency.getAgencyType() == 2) {
                            return R.error("该上级机构类型错误");
                        }
                    }
                }
                if (null == parentId) {
                    if (agencyType == 1) {
                        parentId = 0L;
                    }
                    if (agencyType == 2) {
                        return R.error(400, "请选择上级物业");
                    }
                }
                editTag = true;
                oldEstateAgency.setAgencyType(agencyType);
                oldEstateAgency.setParentId(parentId);
            }
        }
         /* ==== 上级机构 =====*/
        if (null != parentId) {
            if (!parentId.equals(oldEstateAgency.getParentId())) {
                if (agencyType == 1) {
                    parentId = 0L;
                }
                if (agencyType == 2) {
                    EstateAgency estateAgency = estateAgencyService.selectById(parentId);
                    parameterIsNull(estateAgency, "没有该上级机构信息");
                    if (estateAgency.getAgencyType() == 2) {
                        return R.error("该上级机构类型错误");
                    }
                }
                editTag = true;
                oldEstateAgency.setParentId(parentId);
            }
        }
         /* ==== 机构名称 =====*/
        boolean editAgencyNameTag = false;
        if (StringUtils.isNotBlank(agencyName)) {
            if (!agencyName.equals(oldEstateAgency.getAgencyName())) {
                int countAgencyName = 0;
                if (oldEstateAgency.getAgencyType() == 1) {
                    countAgencyName = estateAgencyService.selectCount(new EntityWrapper<EstateAgency>().eq("agency_name", agencyName));
                }
                if (oldEstateAgency.getAgencyType() == 2) {
                    countAgencyName = estateAgencyService.selectCount(new EntityWrapper<EstateAgency>().eq("agency_name", agencyName).eq("parent_id", parentId));
                }
                if (countAgencyName > 0) {
                    return R.error(400, "该机构名称已存在");
                }
                editTag = true;
                if (oldEstateAgency.getAgencyType() == 2) {
                    editAgencyNameTag = true;
                }
                oldEstateAgency.setAgencyName(agencyName);
            }
        }
         /* ==== 机构地址 =====*/
        if (StringUtils.isNotBlank(areaId)) {
            String[] areaIdArr = areaId.split("-");
            if (areaIdArr.length < 3) {
                return R.error(400, "请选择完整机构地址");
            }
            for (int x = 0; x < areaIdArr.length; x++) {
                areaIdArr[x] = areaIdArr[x].trim();
            }
            areaId = areaIdArr[0] + "-" + areaIdArr[1] + "-" + areaIdArr[2];
            if (!areaId.equals(oldEstateAgency.getAreaId())) {
                try {
                    Long threeAreaId = Long.parseLong(areaIdArr[2]);
                    Map<String, Object> areaInfoMap = cnareaSevice.selectThreeParentArea(threeAreaId);
                    if (null == areaInfoMap) {
                        return R.error(400, "未查询到该地址信息");
                    }
                    if (areaInfoMap.get("twoAreaId").equals(areaIdArr[1]) && areaInfoMap.get("oneAreaId").equals(areaIdArr[0])) {
                        editTag = true;
                        oldEstateAgency.setAgencyAddress("" + areaInfoMap.get("oneAreaName") + areaInfoMap.get("twoAreaName") + areaInfoMap.get("threeAreaName"));
                        oldEstateAgency.setAreaLongitude(Double.parseDouble(areaInfoMap.get("threeAreaLng").toString()));
                        oldEstateAgency.setAreaLatitude(Double.parseDouble(areaInfoMap.get("threeAreaLat").toString()));//设置机构地址经纬度
                        oldEstateAgency.setAreaId(areaId);//设置机构地址编号
                    } else {
                        return R.error(400, "错误的地址信息");
                    }
                } catch (NumberFormatException ex) {
                    return R.error(400, "错误的地址信息");
                } catch (NullPointerException ex) {
                    return R.error(400, "未查询到该地址信息");
                }
            }
        }
        if (editTag) {
            estateAgencyService.updateById(oldEstateAgency);
            if (editAgencyNameTag) {
                //修改 关联表社区名称
                estateAgencyService.updateJoinTableCommunityName(oldEstateAgency.getAgencyName(), oldEstateAgency.getAgencyId());
              // 修改 卡片关联显示的 社区名称
                estateAgencyService.updateCardJoinTableCommunityName(oldEstateAgency.getAgencyId());
            }
        }
        return R.ok();
    }

    @ApiOperation(value = "分页查询机构")
    @RequestMapping(value = "/readPage", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "请求条数(默认10)", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "pageNum", value = "请求页数(默认1)", required = false, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "parentId", value = "上级机构id", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "agencyName", value = "机构名称", required = false, dataType = "int", paramType = "form"),
    })
    public R readPage(Integer pageNum, Integer pageSize, String parentId, String agencyName) {
        if (null == pageNum || pageNum < 1) {
            pageNum = 1;
        }
        if (null == pageSize || pageSize < 1) {
            pageSize = 10;
        }
        Page<EstateAgency> page = new Page<EstateAgency>(pageNum, pageSize);
        Wrapper<EstateAgency> wrapper = new EntityWrapper<EstateAgency>();
        if (StringUtils.isNotBlank(parentId)) {
            wrapper.eq("parent_id", parentId);
        }
        if (StringUtils.isNotBlank(agencyName)) {
            wrapper.like("agency_name", agencyName);
        }
        Page<EstateAgency> returnPage = estateAgencyService.selectPage(page, wrapper);
        return R.ok().put("data",returnPage).putMpPageDescription().putDescription(EstateAgency.class);
    }

    @ApiOperation(value = "查询机构")
    @RequestMapping(value = "/readList", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "上级机构id", required = false, dataType = "long", paramType = "form"),
            @ApiImplicitParam(name = "agencyType", value = "机构类型", required = false, dataType = "String", paramType = "form"),
    })
    public R readList(Long parentId, Integer agencyType) {
        if (null != agencyType) {
            if (agencyType != 2) {
                agencyType = 1;
            }
        }
        Wrapper<EstateAgency> wrapper = new EntityWrapper<EstateAgency>();
        if (null != parentId) {
            wrapper.eq("parent_id", parentId);
        }
        if (null != agencyType) {
            wrapper.eq("agency_type", agencyType);
        }
        List<EstateAgency> returnPage = estateAgencyService.selectList(wrapper);
        return R.ok().put("data",returnPage).putDescription(EstateAgency.class);
    }

    @ApiOperation(value = "禁/启用机构")
    @RequestMapping(value = "/changeAgencyType", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "agencyId", value = "机构id", required = false, dataType = "String", paramType = "form"),
    })
    public R changeAgencyType(String agencyId) {
        parameterIsBlank(agencyId, "请选择机构");
        EstateAgency agency = estateAgencyService.selectById(agencyId);
        parameterIsNull(agency, "暂无该机构信息");
        if (null != agency.getAgencyState() && agency.getAgencyState() == 2) {
            agency.setAgencyState(1);
        } else {
            agency.setAgencyState(2);
        }
        estateAgencyService.updateById(agency);
        return R.ok();
    }
}
